# _*_ coding:utf-8 _*_

"""
# @Time　 : 2021/12/28 21:38
# @Author : king
# @File　 : data_handle.py
# @project: ApiPytestFramework
# @QQ     : 772084279
# @Email  : 772084279@qq.com
# @blog   : https://ceshizhilu.blog.csdn.net/
"""
import os
import re
from jsonpath import jsonpath

from outputs.Logs.log_handle import get_log

logging = get_log(os.path.split(__file__)[-1])


def json_extractor(obj: dict, expr: str = '.') -> object:
    """
    :param obj :json/dict类型数据
    :param expr: 表达式, . 提取字典所有内容， $.test_case 提取一级字典case， $.test_case.data 提取case字典下的data
    :return result: 提取的结果，未提取到返回 None
    """
    try:
        result = jsonpath(obj, expr)[0]
        logging.info("提取响应内容成功，提取表达式为： {} 提取值为 {}".format(expr, result))
    except Exception as e:
        logging.exception(e)
        logging.exception(f'未提取到内容，请检查表达式是否错误！提取表达式为：{expr} 提取数据为 {obj}')
        result = None
    return result


def re_extract(obj: str, expr: str = '.') -> object:
    """
    :param obj : 字符串数据
    :param expr: 正则表达式
    :return result: 提取的结果，未提取到返回 None
    """
    try:
        result = re.findall(expr, obj)[0]
    except Exception as e:
        result = None
        logging.exception(e)
        logging.exception(f'未提取到内容，请检查表达式是否错误！提取表达式为：{expr} 提取数据为 {obj}')
    return result
